# -*- coding: utf-8 -*-
from templates.basetemplates import basetemplates
try:
  from cStringIO import StringIO
except:
  from StringIO import StringIO
class PymuqueXmlTemplate(basetemplates):
  def __init__(self,logger,mimetype="text/xml",encoding="utf-8"):
    basetemplates.__init__(self,logger,mimetype,encoding)
    self.logger.debug("%s Init"%(__name__))
  def prepare_render(self,headers,envrequests,sources,sort_sources):
    self.logger.debug("Start Render %s"%__name__)
    out=u""
    out+=u"<?xml version=\"1.0\" encoding=\"utf-8\"?><response>\n"
    if len(headers):
        out+=u" <headers>\n"
        for h in headers:
          out+=u" <header name=\"%s\">%s</header>"%(h,headers[h])
        out+=u" </headers>\n"
    else:
      out+=u" <headers/>\n"
    if len(envrequests):
        out+=u" <requests>\n"
        for r in envrequests:
          out+=u" <request name=\"%s\">%s</request>"%(r,envrequests[r])
        out+=u" </requests>\n"
    else:
      out+=u" <requests/>\n"
    #import pprint
    #pprint.pprint(sources)
    out+=u" <results>\n"
    for s in sort_sources:
      s=s[0]
      if sources[s]['obj'] is not None:
        source=sources[s]['obj']
        err=source.getError()
        if err is None:
          out+=u" <result name=\"%s\"  prefix=\"%s\" type=\"%s\" error=\"false\"><![CDATA[%s]]>"%(s,sources[s]['prefix'],sources[s]['out'],source.result)
          #out+=u" <result name=\"%s\"  prefix=\"%s\" type=\"%s\" error=\"false\">%s"%(s,sources[s]['prefix'],sources[s]['out'],source.result)
        else:
          out+=u" <result name=\"%s\" prefix=\"%s\" type=\"str\" error=\"true\"><![CDATA[%s]]>"%(s,sources[s]['prefix'],err)
        out+=u" </result>"
    out+=u" </results></response>"
    self.out=out


class PymuquePlainTemplate(basetemplates):
  def __init__(self,logger,mimetype="text/xml",encoding="utf-8"):
    basetemplates.__init__(self,logger,mimetype,encoding)
    self.logger.debug("%s Init"%(__name__))
  def prepare_render(self,headers,envrequests,sources,sort_sources):
    self.logger.debug("Start Render %s"%__name__)
    out=u""
    if len(headers):
        out+=u"\n#### headers\n"
        for h in headers:
          out+=u"## %s #@# %s\n"%(h,headers[h])
    if len(envrequests):
        out+=u"\n#### requests\n"
        for r in envrequests:
          out+=u"## %s #@# \n%s"%(r,envrequests[r])
    out+=u"\n#### results\n"
    for s in sort_sources:
      s=s[0]
      if sources[s]['obj'] is not None:
        source=sources[s]['obj']
        err=source.getError()
        if err is None:
          out+=u"## name#@#{%s} prefix#@#{%s} type#@#%s error#@#false #{{<[[%s]]]>}}#\n"%(s,sources[s]['prefix'],sources[s]['out'],source.result)
        else:
          out+=u"## name#@#{%s} prefix#@#{%s} type#@#str error#@#false #{{<[[%s]]]>}}#\n"%(s,sources[s]['prefix'],err)
    
    self.out=out
